# main.jl

# This is the main julia script that runs the structural estimation

# Before running this, instantiate the package directory and set the root paths correctly below

# Note: in these comments, Z_F refers to what is called z^(2) in the paper

# To replicate the comparison with a noisy version of the z measures (Appendix F.3), replace the
# files in this directory with the ones in the "julia_noise" subdirectory

# The following runs in about a week on a Quad-Core Intel Core i7-6700 with 64 GB RAM (3 days for
# the main specification and 4 days for the CES version)

cd("C:/Users/johannes.boehm/Dropbox/cenf/data/revision-2017/julia")
root = "C:/Users/johannes.boehm/Dropbox/cenf/data/revision-2017"

include("cenf.jl")

cenf.readData(root)

using JuMP
using KNITRO
using MAT
using JLD2
using Gadfly, DataFrames
using Distributed
using Random

# ESTIMATE THE MODEL

# Get more workers
workers = addprocs(8; exeflags="--project")

# do the estimation
include("do_zf.jl")

# remove workers
rmprocs(workers)

# print table with estimation results 
include("estimationResults.jl")

# SIMULATE WELFARE COUNTERFACTUALS

# (ordering of the paper text)
# first approach: hold theta fixed, estimate each d() semiparametrically
include("simulateCounterfactuals_fixedtheta.jl")
# second approach: use functional form from microfoundation, estimate theta
include("simulateCounterfactuals_variabletheta.jl")

using Printf
open("../output/welfaretable.tex","w") do fhh
  for i=1:54
    j = i+55
    write(fhh, @sprintf("%s & %0.2f & %0.1f & %0.1f & %0.1f & %0.1f & %s & %0.2f & %0.1f & %0.1f & %0.1f & %0.1f  \\\\ \n", 
    cenf.countrynames_full[i], cenf.δ[i,1,1],100*changeArray_FF[i,1],100*changeArray_FF[i,2],100*changeArray_VF[i,1],100*changeArray_VF[i,2],
    cenf.countrynames_full[j], cenf.δ[j,1,1],100*changeArray_FF[j,1],100*changeArray_FF[j,2],100*changeArray_VF[j,1],100*changeArray_VF[j,2]))
  end
  i = 55
  write(fhh, @sprintf("%s & %0.2f & %0.1f & %0.1f & %0.1f & %0.1f &  &  & & & & \\\\ \n", 
    cenf.countrynames_full[i], cenf.δ[i,1,1],100*changeArray_FF[i,1],100*changeArray_FF[i,2],100*changeArray_VF[i,1],100*changeArray_VF[i,2]))
end

# CES ESTIMATION AND COUNTERFACTUALS

# estimation
include("do_ces_zf_rhothetafixed.jl")
# counterfactuals
include("simulateCounterfactuals_ces.jl")

# AUXILIARY CODE 

# Ref 3, resampling estimator
include("bootstrap.jl")